/**
 * 微信定义的，包名类名都不能改
 */

package com.elong.android.specialhouse.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.dp.android.elong.crash.LogWriter;
import com.elong.android.specialhouse.base.DialogUtils;
import com.elong.android.specialhouse.utils.StringUtils;
import com.elong.android.specialhouse.utils.Utils;
import com.elong.payment.base.PaymentConstants;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

	private IWXAPI api;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		api = WXAPIFactory.createWXAPI(this, PaymentConstants.WEIXIN_APPID);
		api.handleIntent(getIntent(), this);

		String wxPaymentUrl = getIntent().getStringExtra("wxPaymentUrl");
		if (!StringUtils.isEmpty(wxPaymentUrl)) {
			gotoWeixin(wxPaymentUrl);
		}
	}

	private void gotoWeixin(String wxPaymentUrl) {
		if (Utils.isEmptyString(wxPaymentUrl)) {
			DialogUtils.showInfo(this, "提示", " 未能获取支付页面");
			finish();
			return;
		}
		JSONObject json = null;
		PayReq req = new PayReq();
		try {
			json = JSONObject.parseObject(wxPaymentUrl);
			req.appId = PaymentConstants.WEIXIN_APPID;
			req.partnerId = json.getString("partnerId");// 商家向财付通申请的商家id
			req.prepayId = json.getString("prepayId");
			req.nonceStr = json.getString("nonceStr");
			req.timeStamp = json.getString("timeStamp");
			req.packageValue = json.getString("package");
			req.sign = json.getString("sign");
		} catch (JSONException e) {
			DialogUtils.showInfo(this, "提示", "支付页面解析错误");
			finish();
			return;
		}
		// 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
		try {
			IWXAPI api = WXAPIFactory.createWXAPI(WXPayEntryActivity.this, PaymentConstants.WEIXIN_APPID);
			api.registerApp(PaymentConstants.WEIXIN_APPID);
			api.sendReq(req);
		} catch (Exception e) {
			LogWriter.logException("", 0, e);
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		api.handleIntent(intent, this);
	}

	@Override
	public void onReq(BaseReq req) {
	}

	@Override
	public void onResp(BaseResp resp) {
		boolean isSuccess = resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX && resp.errCode == 0;
		WXSharedPreferencesTools.getInstance().setWXPayResult(this, isSuccess);
		setResult(isSuccess ? RESULT_OK : RESULT_CANCELED);
		finish();
	}

	private boolean leavePageNext = false; // 默认是进入页面

	@Override
	protected void onResume() {
		if (leavePageNext) {
			finish();
		}

		leavePageNext = true;

		super.onResume();
	}

}